<template>
	<view class="add-container">
		<view class="header">
			<text class="title">添加菜品</text>
			<button class="back-btn" @click="handleBack">返回</button>
		</view>

		<view class="content">
			<view class="form-card">
				<view class="form-header">
					<text class="form-title">菜品信息</text>
				</view>

				<view class="form-body">
					<view class="form-item">
						<text class="label required">菜品名称</text>
						<input 
							v-model="formData.name" 
							class="input" 
							placeholder="请输入菜品名称"
							maxlength="50"
						/>
						<text class="error" v-if="errors.name">{{ errors.name }}</text>
					</view>

					<view class="form-item">
						<text class="label required">菜品分类</text>
						<picker 
							mode="selector" 
							:range="categoryOptions" 
							range-key="name"
							@change="handleCategoryChange"
							:value="categoryIndex"
						>
							<view class="picker">
								{{ categoryIndex >= 0 ? categoryOptions[categoryIndex].name : '请选择分类' }}
							</view>
						</picker>
						<text class="error" v-if="errors.category_id">{{ errors.category_id }}</text>
					</view>

					<view class="form-item">
						<text class="label">菜品图片</text>
						<view class="image-upload">
							<input 
								v-model="formData.image" 
								class="input" 
								placeholder="请输入图片URL（可选）"
							/>
							<button class="preview-btn" @click="previewImage" v-if="formData.image">预览</button>
						</view>
						<view class="image-preview" v-if="formData.image">
							<image :src="formData.image" mode="aspectFit" class="preview-image"></image>
						</view>
					</view>

					<view class="form-item">
						<text class="label">菜品描述</text>
						<textarea 
							v-model="formData.description" 
							class="textarea" 
							placeholder="请输入菜品描述"
							maxlength="200"
						/>
						<text class="char-count">{{ formData.description?.length || 0 }}/200</text>
					</view>

					<view class="form-item">
						<text class="label">主材</text>
						<textarea 
							v-model="formData.ingredients.main_ingredients" 
							class="textarea" 
							placeholder="请输入主材（可选）"
							maxlength="500"
						/>
					</view>

					<view class="form-item">
						<text class="label">辅材</text>
						<textarea 
							v-model="formData.ingredients.auxiliary_ingredients" 
							class="textarea" 
							placeholder="请输入辅材（可选）"
							maxlength="500"
						/>
					</view>

					<view class="form-item">
						<text class="label">调味品</text>
						<textarea 
							v-model="formData.ingredients.seasonings" 
							class="textarea" 
							placeholder="请输入调味品（可选）"
							maxlength="500"
						/>
					</view>

					<view class="form-item">
						<text class="label required">辣度</text>
						<view class="radio-group">
							<label class="radio-label">
								<radio :checked="formData.spiciness === 0" @click="formData.spiciness = 0" />
								<text>不辣</text>
							</label>
							<label class="radio-label">
								<radio :checked="formData.spiciness === 1" @click="formData.spiciness = 1" />
								<text>微辣</text>
							</label>
							<label class="radio-label">
								<radio :checked="formData.spiciness === 2" @click="formData.spiciness = 2" />
								<text>中辣</text>
							</label>
							<label class="radio-label">
								<radio :checked="formData.spiciness === 3" @click="formData.spiciness = 3" />
								<text>重辣</text>
							</label>
						</view>
						<text class="error" v-if="errors.spiciness">{{ errors.spiciness }}</text>
					</view>

					<view class="form-item">
						<text class="label">是否推荐</text>
						<switch :checked="formData.is_recommended" @change="onRecommendChange" />
					</view>
				</view>

				<view class="form-actions">
					<button class="btn btn-cancel" @click="handleBack">取消</button>
					<button class="btn btn-submit" @click="handleSubmit">提交</button>
				</view>
			</view>
		</view>

		<!-- 图片预览弹窗 -->
		<uni-popup ref="imagePopup" type="center">
			<view class="image-modal">
				<image :src="formData.image" mode="aspectFit" class="modal-image"></image>
				<button class="close-btn" @click="closeImagePreview">关闭</button>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const formData = reactive({
  name: '',
  category_id: '',
  description: '',
  image: '',
  ingredients: {
    main_ingredients: '',
    auxiliary_ingredients: '',
    seasonings: ''
  },
  spiciness: 0,
  is_recommended: false
})

const errors = reactive({})
const categoryOptions = ref([])
const categoryIndex = ref(-1)

const imagePopup = ref(null)

// 加载分类选项
async function loadCategories() {
  try {
    const result = await uniCloud.callFunction({
      name: 'food-categories',
      data: {
        action: 'get-categories',
        pageSize: 100
      }
    })

    if (result.result && result.result.code === 200) {
      categoryOptions.value = result.result.data?.list || []
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 分类选择
function handleCategoryChange(e) {
  categoryIndex.value = e.detail.value
  if (categoryIndex.value >= 0) {
    formData.category_id = categoryOptions.value[categoryIndex.value]._id
  } else {
    formData.category_id = ''
  }
}

// 表单验证
function validateForm() {
  Object.keys(errors).forEach(k => delete errors[k])
  let isValid = true

  // 验证菜品名称
  if (!formData.name.trim()) {
    errors.name = '菜品名称不能为空'
    isValid = false
  } else if (formData.name.trim().length > 50) {
    errors.name = '菜品名称不能超过50个字符'
    isValid = false
  }

  // 验证分类
  if (!formData.category_id) {
    errors.category_id = '请选择菜品分类'
    isValid = false
  }

  // 验证辣度
  const s = parseInt(formData.spiciness)
  if (isNaN(s) || s < 0 || s > 3) {
    errors.spiciness = '辣度必须是0-3之间的整数'
    isValid = false
  }

  return isValid
}

// 提交表单
async function handleSubmit() {
  if (!validateForm()) {
    return
  }

  uni.showLoading({
    title: '提交中...'
  })

  try {
    const submitData = {
      name: formData.name.trim(),
      category_id: formData.category_id,
      description: formData.description?.trim() || '',
      image: formData.image || '',
      ingredients: {
        main_ingredients: formData.ingredients.main_ingredients?.trim() || '',
        auxiliary_ingredients: formData.ingredients.auxiliary_ingredients?.trim() || '',
        seasonings: formData.ingredients.seasonings?.trim() || ''
      },
      spiciness: parseInt(formData.spiciness),
      is_recommended: !!formData.is_recommended
    }

    const result = await uniCloud.callFunction({
      name: 'food-dishes',
      data: {
        action: 'add-dish',
        data: { dishData: submitData }
      }
    })
	
    if (result.result && result.result.code === 200) {
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/dishes/list' })
      }, 1200)
    } else {
      uni.showToast({
        title: result.result?.message || '添加失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('添加菜品失败:', error)
    uni.showToast({
      title: '添加失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 返回
function handleBack() {
  uni.redirectTo({ url: '/pages/dishes/list' })
}

// 图片预览
function previewImage() {
  if (formData.image) {
    imagePopup.value?.open()
  }
}

function closeImagePreview() {
  imagePopup.value?.close()
}

function onRecommendChange(e) {
  formData.is_recommended = !!(e && e.detail && e.detail.value)
}

onLoad(() => {
  loadCategories()
})
</script>

<style lang="scss" scoped>
	.add-container {
		min-height: 100vh;
		background-color: #f5f5f5;

		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			background: white;
			border-bottom: 1rpx solid #eee;

			.title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}

			.back-btn {
				padding: 16rpx 32rpx;
				background: #f0f0f0;
				border: none;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #666;
				cursor: pointer;
			}
		}

		.content {
			padding: 20rpx;

			.form-card {
				background: white;
				border-radius: 12rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

				.form-header {
					padding: 30rpx;
					border-bottom: 1rpx solid #eee;

					.form-title {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
					}
				}

				.form-body {
					padding: 30rpx;

					.form-item {
						margin-bottom: 40rpx;

						&:last-child {
							margin-bottom: 0;
						}

						.label {
							display: block;
							font-size: 28rpx;
							color: #333;
							margin-bottom: 15rpx;

							&.required::after {
								content: '*';
								color: #ff4d4f;
								margin-left: 5rpx;
							}
						}

						.input {
							width: 100%;
							padding: 20rpx;
							border: 1rpx solid #d9d9d9;
							border-radius: 8rpx;
							font-size: 28rpx;
							color: #333;

							&:focus {
								border-color: #007aff;
							}
						}

						.textarea {
							width: 100%;
							padding: 20rpx;
							border: 1rpx solid #d9d9d9;
							border-radius: 8rpx;
							font-size: 28rpx;
							color: #333;
							min-height: 120rpx;
							resize: vertical;

							&:focus {
								border-color: #007aff;
							}
						}

						.char-count {
							display: block;
							text-align: right;
							font-size: 24rpx;
							color: #999;
							margin-top: 10rpx;
						}

						.picker {
							padding: 20rpx;
							border: 1rpx solid #d9d9d9;
							border-radius: 8rpx;
							font-size: 28rpx;
							color: #333;
							background: white;
						}

						.image-upload {
							display: flex;
							gap: 15rpx;

							.preview-btn {
								padding: 16rpx 24rpx;
								background: #007aff;
								color: white;
								border: none;
								border-radius: 6rpx;
								font-size: 26rpx;
								cursor: pointer;
							}
						}

						.image-preview {
							margin-top: 15rpx;

							.preview-image {
								width: 200rpx;
								height: 150rpx;
								border-radius: 8rpx;
								border: 1rpx solid #eee;
							}
						}

						.radio-group {
							display: flex;
							gap: 30rpx;

							.radio-label {
								display: flex;
								align-items: center;
								gap: 10rpx;
								font-size: 28rpx;
								color: #333;
								cursor: pointer;
							}
						}

						.error {
							display: block;
							font-size: 24rpx;
							color: #ff4d4f;
							margin-top: 10rpx;
						}
					}
				}

				.form-actions {
					display: flex;
					gap: 20rpx;
					padding: 30rpx;
					border-top: 1rpx solid #eee;

					.btn {
						flex: 1;
						padding: 24rpx;
						border: none;
						border-radius: 8rpx;
						font-size: 28rpx;
						cursor: pointer;

						&.btn-cancel {
							background: #f0f0f0;
							color: #666;
						}

						&.btn-submit {
							background: #007aff;
							color: white;
						}
					}
				}
			}
		}

		.image-modal {
			background: white;
			border-radius: 12rpx;
			padding: 30rpx;
			text-align: center;

			.modal-image {
				width: 400rpx;
				height: 300rpx;
				border-radius: 8rpx;
				margin-bottom: 20rpx;
			}

			.close-btn {
				padding: 16rpx 32rpx;
				background: #007aff;
				color: white;
				border: none;
				border-radius: 8rpx;
				font-size: 28rpx;
				cursor: pointer;
			}
		}

		@media (max-width: 750rpx) {
			.add-container {
				padding: 15rpx;

				.header {
					padding: 15rpx;

					.title {
						font-size: 32rpx;
					}

					.back-btn {
						padding: 12rpx 24rpx;
						font-size: 26rpx;
					}
				}

				.content {
					padding: 15rpx;

					.form-card {
						.form-header {
							padding: 20rpx;

							.form-title {
								font-size: 30rpx;
							}
						}

						.form-body {
							padding: 20rpx;

							.form-item {
								margin-bottom: 30rpx;

								.image-upload {
									flex-direction: column;
									gap: 10rpx;

									.preview-btn {
										width: 100%;
									}
								}
							}
						}

						.form-actions {
							padding: 20rpx;
							flex-direction: column;
							gap: 15rpx;
						}
					}
				}

				.image-modal {
					padding: 20rpx;

					.modal-image {
						width: 300rpx;
						height: 200rpx;
					}
				}
			}
		}
	}
</style>